package com.sp2p.action.front;

import java.io.IOException;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.shove.Convert;
import com.shove.data.DataException;
import com.shove.util.SqlInfusion;
import com.shove.web.util.JSONUtils;
import com.sp2p.constants.IAmountConstants;
import com.sp2p.constants.IConstants;
import com.sp2p.entity.User;
import com.sp2p.service.AssignmentDebtService;
import com.sp2p.service.FinanceService;
import com.sp2p.service.HomeInfoSettingService;
import com.sp2p.service.MyHomeService;
import com.sp2p.service.NewsAndMediaReportService;
import com.sp2p.service.PublicModelService;
import com.sp2p.service.UserService;
import com.sp2p.service.admin.BorrowManageService;
import com.sp2p.util.DateUtil;
import com.sp2p.util.MoneyUtil;

/**
 * 信息管理模块
 * 
 * @author Administrator
 * 
 */
public class FrontMessageAction extends BaseFrontAction {

	private static final long serialVersionUID = 1L;
	public static Log log = LogFactory.getLog(FrontMessageAction.class);
	private BorrowManageService borrowManageService;
	private PublicModelService publicModelService;
	private FinanceService financeService;
	private AssignmentDebtService assignmentDebtService;
	private HomeInfoSettingService homeInfoSettingService;
	private  MyHomeService  myHomeService;
	private UserService userService;
	private NewsAndMediaReportService newsService;

	private List<Map<String, Object>> teamList;

	public List<Map<String, Object>> getTeamList() {
		return teamList;
	}

	public MyHomeService getMyHomeService() {
		return myHomeService;
	}

	public void setMyHomeService(MyHomeService myHomeService) {
		this.myHomeService = myHomeService;
	}

	public HomeInfoSettingService getHomeInfoSettingService() {
		return homeInfoSettingService;
	}

	public void setHomeInfoSettingService(
			HomeInfoSettingService homeInfoSettingService) {
		this.homeInfoSettingService = homeInfoSettingService;
	}

	public PublicModelService getPublicModelService() {
		return publicModelService;
	}

	public void setPublicModelService(PublicModelService publicModelService) {
		this.publicModelService = publicModelService;
	}

	public void setTeamList(List<Map<String, Object>> teamList) {
		this.teamList = teamList;
	}
	
	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public void setNewsService(NewsAndMediaReportService newsService) {
		this.newsService = newsService;
	}

	public String initMessage() {
		return SUCCESS;
	}
	
	/**
	 * 根据信息类型查询信息详情
	 * 
	 * @return
	 * @throws SQLException
	 * @throws DataException
	 */
	public String getMessageBytypeId() throws Exception {
		
		Integer typeId = Convert.strToInt(request("typeId"), -1);
		String userId=request("userId");
		if(null==userId){
			userId="0";
		}
		try {
		paramMap = publicModelService.getMessageByTypeId(typeId);
		if(typeId == 21){
			Long investId = Convert.strToLong(request("investId"),-1);
			Map<String,String> map = myHomeService.debtHeTong(investId);
			Map<String,String> regmap = publicModelService.getAgreementDetail(2, 1);
			if(map!=null){
				StringBuffer sb = new StringBuffer();
				sb.append("<div>" +
						"<p>本《债权转让协议》(“本协议”)由以下双方于" +
						"<span>"+map.get("investTimeYear")+"</span>年" +
						"<span>"+map.get("investTimeMonth")+"</span>月" +
						"<span>"+map.get("investTimeDay")+"</span>日签订：</p>" +
						"<p>甲方（转让人/原债权人）："+map.get("zrealName")+"</p>" +
						"<table width='500' border='1' cellspacing='0' cellpadding='0' style='text-align: center;'>" +
						"<tr height='30'>" +
						"<td>共富网用户名</td>" +
						"<td>身份证号码</td>" +
						"</tr>" +
						"<tr height='30'>" +
						"<td>"+map.get("zusername")+"</td>" +
						"<td>"+map.get("zidNo")+"</td>" +
						"</tr>" +
						"</table>" +
						"<p>乙方（受让人/新债权人）："+map.get("srealName")+"</p>" +
						"<p>共富网用户名："+map.get("susername")+"</p>" +
						"<p>身份证号码："+map.get("sidNo")+"</p>" +
						"<p>住所："+map.get("saddress")+"</p>" +
						"<p>电子邮件地址："+map.get("semail")+"</p>" +
						"</div>");
				
				StringBuffer sb2 = new StringBuffer();
				sb2.append("<div>" +
						"<table width='650' cellspacing='0' cellpadding='0' border='1' style='word-break: break-all'>" +
						"<tr style='text-align:center;'>" +
						"<td width='350' colspan='7'>债权基本信息</td>" +
						"<td width='300' colspan='4'>借款人月还款情况下债权收益信息</td>" +
						"</tr>" +
						"<tr>" +
						"<td>编号</td>" +
						"<td>借款人姓名</td>" +
						"<td>身份证号</td>" +
						"<td>初始借款<br/>金额</td>" +
						"<td>债权价值</td>" +
						"<td>需支付对价</td>" +
						"<td>借款用途</td>" +
						"<td>还款起始日期</td>" +
						"<td>还款期限(月)</td>" +
						"<td>剩余还款月数</td>" +
						"<td>预计债权<br/>收益率(年)</td>" +
						"</tr>" +
						"<tr>" +
						"<td>"+map.get("id")+"</td>" +
						"<td>"+map.get("jrealName")+"</td>" +
						"<td>"+map.get("jidNo").substring(0,8)+"<br/>"+map.get("jidNo").substring(8,map.get("jidNo").length())+"</td>" +
						"<td>"+map.get("borrowAmount")+"</td>" +
						"<td>"+(Convert.strToDouble(map.get("recievedPI"), 0)-Convert.strToDouble(map.get("hasP"),0))+"</td>" +
						"<td>"+map.get("auctionBasePrice")+"</td>" +
						"<td>"+map.get("purpose")+"</td>" +
						"<td>"+map.get("investTime")+"</td>" +
						"<td>"+map.get("deadline")+"</td>" +
						"<td>"+map.get("restline")+"</td>" +
						"<td>"+map.get("annualRate")+"</td>" +
						"</tr></table></div>");
				String content = regmap.get("content");
				content = content.replace("[zqperson]", sb);
				content = content.replace("[zqlist]", sb2);
				request().setAttribute("content", content);
			}
		}
		
		} catch (SQLException e) {
			log.error(e);
			e.printStackTrace();
		} catch (DataException e) {
			log.error(e);
			e.printStackTrace();
		} catch (ParseException e) {
			log.error(e);
			e.printStackTrace();
		}
		/*add by sunbing start*/
		request().setAttribute("typeId", typeId);
		/*add by sunbing end*/
		
		if (typeId == 1) {
			return "jkxy"; // 借款协议
		} else if (typeId == 2) {
			return "gsjj"; // 公司简介
		} else if (typeId == 3) {
			return "ptyl"; // 平台原理
		} else if (typeId == 4) {
			//总投资用户数
			Map<String,String> userCountMap = userService.queryUserCount();	
			request().setAttribute("userCount", userCountMap.get("nums"));
			//投资总额
			Map<String,String> financeEarnMap = financeService.queryTotalInvest();
			request().setAttribute("investAmount", financeEarnMap.get("totalInvestAmount"));
			//媒体报道 取3条记录
			pageBean.setPageSize(3);
			newsService.queryMediaReportPage(pageBean);		
			List<Map<String, Object>> meikuList = pageBean.getPage();
			pageBean.setPage(null);
			request().setAttribute("meikuList", meikuList);
			return "gywm"; // 关于我们
		} else if (typeId == 5) {
			return "flfg"; // 法律法规
		} else if (typeId == 6) {
			return "tdjs"; // 团队介绍
		} else if (typeId == 7) {
			return "lxwm"; // 联系我们
		} else if (typeId == 8) {// 理财攻略
			return "lcgl";
		} else if (typeId == 9) {// 网站地图
			return "wzdt";
		} else if (typeId == 10) {//诚聘英才
			return "cpyc";
		} else if (typeId == 11) {// 合作伙伴
			return "hzhb";
		} else if (typeId == 13) {// 专家顾问
			return "zjgw";
		} else if (typeId == 15) {// 借款协议
			return "jkxy";
		} else if (typeId == 16) {// 网站声明
			return "wzsm";
		} else if (typeId == 17) {// 操作演示
			return "czys";
		} else if (typeId == 18) {// 新手指引
			return "xszy";
		} else if (typeId == 19) {// 友情链接
			return "yqlj";
		} else if (typeId == 21) {//债权转让协议
			return "zqzr";
		}else if (typeId == 22) {//共富网投资咨询与管理服务协议
			return "tzzx-glfw";
		}else if (typeId == 23) {//高收益低门槛
			return "yield";
		}else if (typeId == 24) {//最安全网上理财
			return "security";
		}else if (typeId == 25) {//随时随地赎回投资
			return "redemption";
		} else if (typeId == 26) {//理财大揭秘
			return "lcxwdjm";
		}else if (typeId == 27) {//共富喜迎各界首肯
			return "gjsk";
		}else if (typeId == 28) {//共富网2014年阶段发展报告
			return "jianbao";
		}else if (typeId == 29) {//可信网站
			return "kexin";
		}else if (typeId == 30) {//月月回本息
			return "benxi";
		}else {
			return SUCCESS;
		}

	}
	
	public String queryteamList() throws Exception{
		publicModelService.queryTeamPage(pageBean);
		return SUCCESS;
	}

	
	/**
	 * 根据信息类型查询信息详情
	 * 
	 * @return
	 * @throws Exception
	 */
	public String qureygetMessageBytypeId() {
		Integer typeId = Convert.strToInt(request("typeId"), -1);
		try {
			Map<String, String> map = null;
			map = publicModelService.getMessageByTypeId(typeId);
			JSONUtils.printObject(map);
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
		}
		return null;

	}
	/***
	 * 查看借款合同
	 * @return
	 * @throws Exception 
	 */
//	public String jiekuanhetong() throws Exception{
//		Long borrowId = Convert.strToLong(request("borrowId"),0);
//		// 借款详细
//		Map<String, String> borrowDetailMap = financeService.queryBorrowDetailById(borrowId);
//		String moneyChinese="";
//		if(borrowDetailMap!=null){
//			String moneyStr = borrowDetailMap.get("borrowAmount");
//			if(!moneyStr.equals("")&&moneyStr!=null){
//				moneyStr = moneyStr.replace(",", "");
//				Double money = Convert.strToDouble(moneyStr,-1.00);
//				moneyChinese = MoneyUtil.amountToChinese(money);
//				borrowDetailMap.put("amountLength", moneyStr.length()+"");
//			}
//
////			if (borrowDetailMap.get("moneyPurposes").toString().length() > 15) {
////				String moneyPurposes = borrowDetailMap.get("moneyPurposes").toString().substring(0, 15);
////				borrowDetailMap.put("moneyPurposes", moneyPurposes + "…");
////			}
//		}
//		
//		//担保人信息
//		String roletype = borrowDetailMap.get("roletype");
//		if(roletype.equals("1")){
//			borrowDetailMap.put("dname", borrowDetailMap.get("personname"));
//			borrowDetailMap.put("licenceNo", borrowDetailMap.get("idNo"));
//		}else{
//			borrowDetailMap.put("dname", borrowDetailMap.get("companyname"));
//			borrowDetailMap.put("licenceNo", borrowDetailMap.get("businesslicence"));
//		}
//		
//		// 借款人资料
//		Map<String, String> borrowUserMap = financeService
//				.queryUserInfoById(borrowId);
//		// 投资记录
//		List<Map<String, Object>> investList = financeService
//				.queryInvestByid(borrowId);
//		
//		User user = (User) session().getAttribute("user");
//		if(user==null){
//			return "login";
//		}
//		Map<String, String> userMap = null;
//		for (Map<String, Object> map : investList) {
//			String fullname = (String) map.get("fullname");
//			if(null!=fullname&&fullname.equals(user.getUserName())){
//				userMap = homeInfoSettingService.getRealNameByUserId(user.getId());
//			}
//			double recievedInterest = Convert.strToDouble(map.get("recievedInterest").toString(),-1.00);//到期应收的利息
//			double recivedPrincipal = Convert.strToDouble(map.get("recivedPrincipal").toString(),-1.00);//到期应收本金
//			int deadline = Convert.strToInt(map.get("deadline").toString(), 0);//期数
//			double everyInterest = recievedInterest/deadline;//每期应收利息
//			double everyAll = (recievedInterest+recivedPrincipal)/deadline;//每期应收本息
//			
//			map.put("recievedInterest", String.format("%.2f", recievedInterest));
//			map.put("recivedPrincipal", String.format("%.2f", recivedPrincipal));
//			map.put("everyInterest", String.format("%.2f", everyInterest));
//			map.put("everyAll", String.format("%.2f", everyAll));
//		}
//		
//		Map<String,String> mapAmount = financeService.queryEveryAmountById(borrowId);
//		String chineseForPI = "";
//		if(mapAmount!=null){
//			String forPI = mapAmount.get("forPI");
//			if(!forPI.equals("")&&forPI!=null){
//				forPI = forPI.replace(",", "");
//				Double money = Convert.strToDouble(forPI,-1.00);
//				chineseForPI = MoneyUtil.amountToChinese(money);
//				mapAmount.put("forPILength", forPI.length()+"");
//			}
//		}
//		
//		Map<String,String> map = borrowManageService.queryBorrowInfo(borrowId);
//		Map<String,String> regmap = publicModelService.getAgreementDetail(1, 1);
//		request().setAttribute("regMap", regmap);
//		
//		request().setAttribute("investTime", borrowDetailMap.get("auditTime"));
//		request().setAttribute("investList", investList);
//		request().setAttribute("borrowUserMap", borrowUserMap);
//		request().setAttribute("borrowDetailMap", borrowDetailMap);
//		request().setAttribute("map", map);
//		request().setAttribute("moneyChinese", moneyChinese);
//		request().setAttribute("mapAmount", mapAmount);
//		request().setAttribute("chineseForPI", chineseForPI);
//		request().setAttribute("userMap", userMap);
//		return SUCCESS;
//	}
	
	/***
	 * 获取注册协议
	 * @throws Exception 
	 */
	public String regAgreement() throws Exception{
		Map<String,String> map = publicModelService.getAgreementDetail(5, 1);
		request().setAttribute("regMap", map);
		return SUCCESS;
	}
	/***
	 * 获取投资服务协议
	 * @return
	 * @throws Exception 
	 */
	public String investAgreement() throws Exception{
		String username = request("username");
		String email = request("email");
		Map<String,String> map = publicModelService.getAgreementDetail(6, 1);
		request().setAttribute("regMap", map);
		request().setAttribute("username", username);
		request().setAttribute("email", email);
		return SUCCESS;
	}
	
	/**
	 * 分页查询团队介绍信息
	 * 
	 * @return
	 * @throws SQLException
	 * @throws DataException
	 */
	public String listTeamPage() throws SQLException, DataException {
		try {
			teamList = publicModelService.findListTeam();
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
		}

		return SUCCESS;
	}
	/*add by sunbing start*/
	public void homePageInterlinkage() throws Exception{
		//获取友情链接
		JSONObject obj = new JSONObject();
		JSONArray jsonArray = new JSONArray();
		List<Map<String, Object>> linksList = publicModelService.queyLinksInfoList();
		obj.put("linksList", JSONUtils.toJSONArray(linksList));
		JSONUtils.printObject(obj);
	}
	/*add by sunbing end*/
	
	public String qdzm() throws Exception{
		return SUCCESS;
	}
	
	public void applyToRefferee() throws Exception{
		JSONObject obj = new JSONObject();
		User user=(User)session().getAttribute("user");
		if (user == null){
			obj.put("result", "noLogin");
			JSONUtils.printObject(obj);
			return;
		}
		Long userId = user.getId();
		if(user.getReffereeType() > 1){
			obj.put("result", "isRefferee");
			JSONUtils.printObject(obj);
			return;
		}
		
		Long result = myHomeService.applyToRefferee(userId);
		if(result > 0){
			user.setReffereeType(1);
			session().setAttribute("user", user);
			obj.put("result", "success");
		}else{
			obj.put("result", "failed");
			
		}
		JSONUtils.printObject(obj);
	}

	public BorrowManageService getBorrowManageService() {
		return borrowManageService;
	}

	public void setBorrowManageService(BorrowManageService borrowManageService) {
		this.borrowManageService = borrowManageService;
	}

	public FinanceService getFinanceService() {
		return financeService;
	}

	public void setFinanceService(FinanceService financeService) {
		this.financeService = financeService;
	}

	public AssignmentDebtService getAssignmentDebtService() {
		return assignmentDebtService;
	}

	public void setAssignmentDebtService(
			AssignmentDebtService assignmentDebtService) {
		this.assignmentDebtService = assignmentDebtService;
	}

}
